package com.cqhz.quwan.ui.mine

import android.content.Intent
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.AlipayAuthData
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.UserInfoBean
import com.cqhz.quwan.service.API
import com.cqhz.quwan.service.UserService
import com.cqhz.quwan.ui.base.AbsFragmentPagerAdapter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.activity.RechargeActivity
import com.cqhz.quwan.ui.mine.fragment.TransactionRecordFragment
import com.cqhz.quwan.ui.mine.fragment.WonRecordFragment
import com.cqhz.quwan.util.format
import kotlinx.android.synthetic.main.activity_bean.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.event.RespEvent
import me.militch.quickcore.mvp.model.ModelHelper
import me.militch.quickcore.util.ApiException
import javax.inject.Inject

/**
 * 我的趣豆
 * Created by Guojing on 2018/9/6.
 */
class BeanActivity : GoBackActivity(), HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var modelHelper: ModelHelper
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null
    private lateinit var pagerAdapter: AbsFragmentPagerAdapter
    private var currentIndex = 0

    private val fragments = listOf<Fragment>(
            TransactionRecordFragment.new(),
            WonRecordFragment.new()
    )

    private val selectButtons = arrayOf(
            R.id.rb_transaction_record,
            R.id.rb_won_record
    )

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "我的趣豆"
    }

    override fun layout(): Int {
        return R.layout.activity_bean
    }

    override fun initView() {
        loginBean = APP.get()!!.loginInfo
        action_goto_recharge.setOnClickListener { startActivity(Intent(this, RechargeActivity::class.java)) }
        action_goto_diamond.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "趣豆寻宝")
            val url = "${API.findTreasure}?userId=${loginBean!!.userId}"
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        pagerAdapter = AbsFragmentPagerAdapter(supportFragmentManager, fragments)
        vp_record_list.adapter = pagerAdapter
        vp_record_list.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                currentIndex = position
                rg_select_record.check(selectButtons[position])
            }
        })
        rg_select_record.setOnCheckedChangeListener { _, checkedId ->
            val index = selectButtons.indexOf(checkedId)
            currentIndex = index
            vp_record_list.currentItem = index
        }
    }

    private fun requestUserInfo() {
        modelHelper.request(
                modelHelper.getService(UserService::class.java).getUserInfo(loginBean!!.userId ?: ""), {
            userInfoBean = it
            tv_beans.text = "${it.balance?.toDouble()?.format()}"
        }, {
            showRequestError(it)
        })
    }

    private fun bindAlipay(authData: AlipayAuthData) {
        modelHelper.requestByPreHandler(
                modelHelper.getService(UserService::class.java).bindAlipay(
                        loginBean!!.userId ?: "",
                        authData.userId,
                        authData.alipayOpenId,
                        authData.authCode), object : RespEvent<String> {
            override fun isOk(t: String?) {
                requestUserInfo()
            }

            override fun isError(apiException: ApiException?) {
                showRequestError(apiException!!)
            }

        }) { _ -> "" }
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        if (userInfoBean != null) {
            bindAlipay(authData)
        }
    }

    override fun onResume() {
        super.onResume()
        requestUserInfo()
        if (vp_record_list.currentItem == 0) {
            (pagerAdapter.getItem(vp_record_list.currentItem) as TransactionRecordFragment).lazyLoad()
        } else if (vp_record_list.currentItem == 1) {
            (pagerAdapter.getItem(vp_record_list.currentItem) as WonRecordFragment).lazyLoad()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        modelHelper.unBind()
    }
}